package com.hspedu.hspmybatis.sqlsession;

import com.hspedu.hspmybatis.config.Function;
import com.hspedu.hspmybatis.config.MapperBean;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class HspConfiguration {

    private static ClassLoader loader=ClassLoader.getSystemClassLoader();
//读取xml配置并处理
    public Connection build(String resource){
        Connection connection=null;
        try {
            //加载配置的hsp_mybatis.xml并返回对应的InputStream
            InputStream stream = loader.getResourceAsStream(resource);
            //解析hsp_mybatis.xml
            SAXReader reader = new SAXReader();
            Document read = reader.read(stream);
            Element rootElement = read.getRootElement();
            //System.out.println("rootElement==="+rootElement+"====rootElement.getName="+rootElement.getName());
            connection=evalDataSource(rootElement);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return connection;
    }
    private Connection evalDataSource(Element node){
        if (!"database".equals(node.getName())){
            throw new RuntimeException("root节点应该是<database>");
        }
        String driverClassName = null;
        String url = null;
        String username = null;
        String password = null;
        for(Object item:node.elements("property")){
           Element i= (Element)item;
            String name = i.attributeValue("name");
            String value = i.attributeValue("value");
            //判断是否得到name value
            if (name==null||value==null){
                throw new RuntimeException("property没有设置name or value");
            }
            switch (name){
                case "driverClassName" :
                    driverClassName=value;
                    break;
                case "url":
                    url=value;
                    break;
                case "username":
                    username=value;
                    break;
                case "password":
                    password=value;
                    break;
                default:
                    throw new RuntimeException("属性名没有匹配");
            }
        }
        Connection connection =null;
        try {
            Class.forName(driverClassName);
            connection = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return connection;
    }
//读取XXXMapper.xml,创建MapperBean
//    path就是xml的路径加文件名，从类的加载路径开始的，如果放在resource下面直接放文件名就行
    public MapperBean read(String path){
        MapperBean mapperBean = new MapperBean();
        try {
            InputStream stream = loader.getResourceAsStream(path);
            SAXReader reader = new SAXReader();
            Document read = reader.read(stream);
            Element rootElement = read.getRootElement();
            String namespace = rootElement.attributeValue("namespace").trim();
            mapperBean.setInterfaceName(namespace);
            Iterator iterator = rootElement.elementIterator();
            List<Function> functions = new ArrayList<>();
            while (iterator.hasNext()) {
                Element e =  (Element)iterator.next();
                Function function = new Function();
                String sqlType = e.getName().trim();
                String funcName = e.attributeValue("id").trim();
                String resultType = e.attributeValue("resultType").trim();
                //String parameterType = e.attributeValue("parameterType").trim();
                String sql = e.getText().trim();
                function.setFuncName(funcName);
                function.setSql(sql);
                function.setSqlType(sqlType);
                Object instance = Class.forName(resultType).newInstance();
                function.setResultType(instance);
                functions.add(function);

            }
            mapperBean.setFunctions(functions);
            //System.out.println("rootElement===="+rootElement);
            //Connection connection = evalDataSource(rootElement);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return mapperBean;

    }


}
